package com.example.message.common;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Comment：
 * @Author: 邹渺
 * @Date: 2019/3/21
 * @Time: 10:59
 */
public class util {

    static String appKeyID = "32e6d6f69e2fc9fd";
    static String appKey   = "YDGkyspTEyxLvwBzUyrLIX4nyOsgVZLQ";


    static Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");


    public static String translatedChineseCharacters(String valueCn) {

        String res = get(util.creatUrl(valueCn, "zh-CHS", "en"));
        JSONObject jsonObject = JSONObject.parseObject(res);

        String s1 = null;
        try {
            s1 = jsonObject.get("translation").toString();
        } catch (Exception e) {
            System.out.println("错误的 valueCn" + valueCn);
            e.printStackTrace();
        }
        String s2 = s1.substring(2, s1.length() - 2);
        return s2.trim();
    }


    /**
     * 写入文件
     *
     * @param fileName
     * @param content
     */
    public static void appendFile(String fileName, String content) {
        try {
            // 打开一个随机访问文件流，按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度，字节数

            long fileLength = randomFile.length();
            // 将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.write(content.getBytes());
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static Boolean checkConstainCH(String name) {
        Matcher matcher = util.pattern.matcher(name);
        System.out.println();
        return matcher.matches();
    }


    /**
     * get请求，参数拼接在地址上
     *
     * @param url 请求地址加参数
     * @return 响应
     */
    public static String get(String url) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(get);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                result = entityToString(entity);
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static String entityToString(HttpEntity entity) throws IOException {
        String result = null;
        if (entity != null) {
            long lenth = entity.getContentLength();
            if (lenth != -1 && lenth < 2048) {
                result = EntityUtils.toString(entity, "UTF-8");
            } else {
                InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
                CharArrayBuffer buffer = new CharArrayBuffer(2048);
                char[] tmp = new char[1024];
                int l;
                while ((l = reader1.read(tmp)) != -1) {
                    buffer.append(tmp, 0, l);
                }
                result = buffer.toString();
            }
        }
        return result;
    }


    public static void main(String[] args) {

        System.out.print(creatUrl("退稿时间早于", "zh-CHS", "en"));
    }

    /**
     * 生成有道URL
     *
     * @param 要搜索的词
     * @param 源语言
     * @param 目标语言
     * @return
     */
    public static String creatUrl(String query, String from, String to) {

        String salt = String.valueOf(System.currentTimeMillis());
        String sign = md5(appKeyID + query + salt + appKey);
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("sign", sign);
        params.put("salt", salt);
        params.put("appKey", appKeyID);

        String urlStr = "https://openapi.youdao.com/api";
        return getUrlWithQueryString(urlStr, params);

    }

    public static String createParam(String query, String from, String to) {
        String salt = String.valueOf(System.currentTimeMillis());
        String sign = md5(appKeyID + query + salt + appKey);
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("sign", sign);
        params.put("salt", salt);
        params.put("appKey", appKeyID);

        String urlStr = "";
        return getUrlWithQueryString(urlStr, params);
    }

    /**
     * 生成32位md5摘要
     *
     * @param str
     * @return
     */
    public static String md5(String string) {
        if (string == null) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        byte[] btInput = string.getBytes();
        try {
            /** 获得MD5摘要算法的 MessageDigest对象 **/
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            /** 使用指定的字节更新摘要 **/
            mdInst.update(btInput);
            /** 获得密文 **/
            byte[] md = mdInst.digest();
            /** 把密文转换成十六进制的字符串形式 **/
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getUrlWithQueryString(String url, Map<String, String> params) {
        if (params == null) {
            return url;
        }

        StringBuilder builder = new StringBuilder(url);
        if (url.contains("?")) {
            builder.append("&");
        } else {
            builder.append("?");
        }

        int i = 0;
        for (String key : params.keySet()) {
            String value = params.get(key);
            if (value == null) { //过滤空key
                continue;
            }

            if (i != 0) {
                builder.append('&');
            }

            builder.append(key);
            builder.append('=');
            builder.append(encode(value));

            i++;

        }
        return builder.toString();
    }

    /**
     * 进行URL编码
     *
     * @param input
     * @return
     */
    public static String encode(String input) {
        if (input == null) {
            return "";
        }

        try {
            return URLEncoder.encode(input, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return input;
    }


    /**
     * 空格转驼峰法(默认小驼峰)
     *
     * @param line       源字符串
     * @param smallCamel 大小驼峰,是否为小驼峰(驼峰，第一个字符是大写还是小写)
     * @return 转换后的字符串
     */
    public static String underline2Camel(String line, boolean... smallCamel) {
        if (line == null || "".equals(line)) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        String regex = "([A-Za-z\\d]+)( )?";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(line);
        //匹配正则表达式
        while (matcher.find()) {
            String word = matcher.group();
            //当是true 或则是空的情况
            boolean scamel = smallCamel.length == 0 || smallCamel[0];
            if (scamel && matcher.start() == 0) {
                sb.append(Character.toLowerCase(word.charAt(0)));
            } else {
                sb.append(Character.toUpperCase(word.charAt(0)));
            }
            int index = word.lastIndexOf(' ');
            if (index > 0) {
                sb.append(word.substring(1, index).toLowerCase());
            } else {
                sb.append(word.substring(1).toLowerCase());
            }
        }
        return sb.toString();
    }
}